package com.suredy.app.project.service;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.suredy.app.project.model.ProjectCost;
import com.suredy.core.service.BaseSrvWithEntity;

@Service
public class ProjectCostSrv extends BaseSrvWithEntity<ProjectCost> {

	public ProjectCostSrv() {
		this.addAnDefOrder("payTime", true);
	}

	@Override
	public DetachedCriteria getDc(ProjectCost t) {
		DetachedCriteria dc = super.getDc(t);

		if (t == null)
			return dc;

		if (!StringUtils.isBlank(t.getId())) {
			dc.add(Restrictions.eq("id", t.getId()));
		}
		if (!StringUtils.isBlank(t.getName())) {
			dc.add(Restrictions.like("name", t.getName(), MatchMode.ANYWHERE));
		}
		if (t.getProject() != null) {
			dc.add(Restrictions.eq("project", t.getProject()));
		}

		return dc;
	}

	@Transactional
	public boolean deleteWithIds(Object[] ids) {
		if (ids == null || ids.length <= 0)
			return false;

		String tmp = "";
		for (int i = 0; i < ids.length; i++) {
			if (!StringUtils.isBlank(tmp))
				tmp += ",";

			tmp += "?";
		}

		String ql = "DELETE FROM ProjectCost WHERE id in (" + tmp + ")";

		return this.deleteByQL(ql, ids) >= 0;
	}

	@Transactional
	public int updateStatus(String id, boolean status) {
		if (StringUtils.isBlank(id))
			return 0;

		String ql = "UPDATE ProjectCost SET payed=? WHERE id=?";

		return this.updateByQL(ql, status, id);
	}

}
